﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Idlesoft.Utils
{
	public static class TypeExtensions
	{
		public static string Pretty(this Type type)
		{
			string pretty = null;

			if (type.IsArray)		
			{
				pretty = type.GetElementType().Pretty() + "[]";
			}
			else
			{
				switch (type.ToString())
				{
					case "System.Char": pretty = "char"; break;
					case "System.String": pretty = "string"; break;
					case "System.Boolean": pretty = "bool"; break;
					case "System.Int32": pretty = "int"; break;
					case "System.Float": pretty = "float"; break;
					case "System.Double": pretty = "double"; break;
					default: pretty = type.ToString(); break;
				}
			}
			return pretty;
		}
		public static object Default(this Type type)
		{
			if (!type.IsValueType)
				return null;
			else
				return Activator.CreateInstance(type);
		}
		public static bool IsType(this Type type, object test)
		{
			return IsType(type, test.GetType());
		}
		public static bool IsType(this Type type, Type test)
		{
			bool result = test.Equals(type);

			if (!result)
			{
				if (test.IsInterface)
				{
					var interfaces = type.GetInterfaces();
					result = !result && interfaces != null && interfaces.Any(iface => test.Equals(iface));
				}
				else
				{
					var otype = typeof(object);
					var temp = type.BaseType;
					while (!result && temp != null && !temp.Equals(otype))
					{
						result = temp != null && test.Equals(temp);
						temp = temp.BaseType;
					}
				}
			}
			return result;
		}
		public static bool IsType<TType>(this Type type)
		{
			return IsType(type, typeof(TType));
		}
	}
}
